// 封装的请求
import axios from 'axios'
import {
    getToken
} from './auth'
import {
    Toast
} from 'vant';

const instance = axios.create({
    timeout: 5000,
    baseURL: 'http://192.168.12.75:3009' //域名前缀，实际请求的接口地址为baseURL + url
})

//axios的全局拦截
//用户在没有登录的情况下无法访问部分页面
//全局请求拦截
// Add a request interceptor
instance.interceptors.request.use(function (config) {
    // Do something before request is sent
    config.headers['authorization'] = 'Bearer ' + getToken()
    return config;
}, function (error) {
    // Do something with request error
    return Promise.reject(error);
});

//全局响应拦截
// Add a response interceptor
instance.interceptors.response.use(function (response) {
    // Any status code that lie within the range of 2xx cause this function to trigger
    // Do something with response data
    // console.log(response)
    if (response.data.code == 'error') {
        console.log(response)
        Toast.fail(response.data.message);
    }
    return response.data;
}, function (error) {
    // Any status codes that falls outside the range of 2xx cause this function to trigger
    // Do something with response error
    console.dir(error)
    return Promise.reject(error);
});



//get请求
export function get(url, params) {
    return instance.get(url, {
        params, //params: params // 表示url中传递的数据
    })
}
//普通的get请求，用于请求分类的数据
export function allGet(url) {
    return axios.get(url)
}
//post请求
export function post(url, data) {
    return instance.post(url, data)
}

//put请求
export function put(url, data) {
    return instance.put(url, data)
}

//del请求
export function del(url) {
    return instance.delete(url)
}
export default axios;

//设置cookei
export function setCookie(value, n) {
    let obj = {};
    obj.fatherID = value.productCategory._id;
    obj.id = value._id;
    var dates = new Date();
    dates.setDate(dates.getDate() + n);
    let arr = [];
    if (getCookie()) {
        arr = getCookie();
    } else {
        arr = [];
    }
    arr.push(obj)
    document.cookie = `Collection=${JSON.stringify(arr)};expires=${dates}`;
}

//获取cookei
export function getCookie() {
    var cookies = document.cookie;
    var arrs = cookies.split("=");
    // console.log(arrs[1])
    // console.log(JSON.parse(arrs[1]))
    if (arrs[1]) {
        return JSON.parse(arrs[1]);
    }

}

//删除cookies
export function delCookie(value, n) {
    let obj = {};
    obj.fatherID = value._id;
    obj.id = value.productCategory._id;
    var dates = new Date();
    dates.setDate(dates.getDate() + n);
    let arr = [];
    if (getCookie()) {
        arr = getCookie();
    } else {
        arr = [];
    }
    let ji = "";
    for (let i = 0; i < arr.length; i++) {
        if (
            arr[i]._id == obj.id &&
            arr[i].productCategory._id == obj.fatherID
        ) {
            ji = i
        }
    }
    arr.splice(ji, 1)
    arr.push(obj)
    document.cookie = `Collection=${JSON.stringify(arr)};expires=${dates}`;
}